-
Notifications
You must be signed in to change notification settings - Fork 0
feat(api): limit requests, query size and recipe creation; batch inserts #122
Conversation
- Per-client GraphQL request limit (300/min, keyed like the auth limiter behind Apache): 429 with Retry-After and code RATE_LIMITED. - Validation rule rejecting operations with more than 10 aliases, 3 top-level fields, 300 fields after fragment expansion or 8 levels (QUERY_TOO_COMPLEX) before any resolver runs. Introspection is not counted, so GraphiQL keeps working. Bodies over 1 MB are refused (413). - Recipe creation quota per user: 30 per hour (RATE_LIMITED with retryAfterSeconds) and 1000 in total (QUOTA_EXCEEDED), checked under a per-user advisory lock so parallel creates are counted one by one. - Ingredients, instructions and tags are written with one INSERT per table (unnest WITH ORDINALITY) instead of one per row. - Limits are injectable through createApp; the browser test server raises the request limit since all scenarios share 127.0.0.1. - The web client explains RATE_LIMITED (also HTTP 429) and QUOTA_EXCEEDED. Closes #119
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are a couple of issues I'd like addressed before approving:
-
apiLimits.ts:73–74: Introspection fields (__schema,__type) bypass all complexity limits. Attackers could exploit this with large aliased introspection queries. Consider enforcing alias and root-field limits while preserving GraphiQL compatibility. -
app.ts:112–119: The 1 MB body limit relies only onContent-Length. Chunked requests without this header can bypass the limit. The actual received body size should also be enforced. -
app.ts:120–145: Requests are counted before CSRF/content-type validation. Rejected requests can therefore exhaust a client's rate limit and block legitimate requests. Consider validating requests before counting them.
The first two are security-related issues worth fixing before merging. The last is a lower-severity concern but could affect legitimate users.
…imits # Conflicts: # apps/api/src/features/recipes/recipeRepository.ts # scripts/test-recipe-api.ts
Introspection fields (__schema, __type) were skipped entirely by the query limits, so a large aliased introspection query could repeat the whole schema without limit. They now count like any other field for aliases, top-level fields and total size, which also bounds fragment expansion inside them. Only depth is exempt, because GraphiQL's standard introspection query is 15 levels deep (about 230 fields, no aliases) and still passes. Tests: the standard getIntrospectionQuery() is accepted; aliased __schema/__type at the top level, aliases below __schema and a very large nested introspection query are rejected.
…Length The 1 MB limit only looked at the Content-Length header, so a chunked request without it (or one that sent more than it stated) was parsed at any size. The request body is now read through a stream that counts the bytes actually received and fails once over the limit; the request is then answered with 413 and PAYLOAD_TOO_LARGE. The quick Content-Length rejection stays, so honest oversized requests are still refused before any reading. Test: a chunked POST without Content-Length over 1 MB gets 413, and a small chunked POST still succeeds.
…s pass Requests were counted before the CSRF header and content-type checks, so a stream of requests that were refused anyway (403) could use up a client's whole per-minute budget and lock them out. The checks now run first and the request is counted only when they pass, so refused requests cost the client nothing. Test: repeated requests with a wrong header, a wrong content-type or an oversized Content-Length are refused, and the client's full budget is still available afterwards.
|
Follow-up commits addressing review:
dev is also merged in (2bf9cd9). It conflicted in |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll update my review to Approved. Two remaining concerns may still be worth considering before merging:
-
apiLimits.ts:112:__typenamefields are still excluded from complexity limits. An exponential fragment chain using these fields could cause excessive CPU usage without triggeringQUERY_TOO_COMPLEX. Consider including them in the field count and adding a regression test. -
app.ts:145–156: The new validation correctly prevents rejected POST requests from consuming the rate limit. However, GET requests don't have the same checks before rate limiting, so malformed or cross-origin GET requests could still exhaust a client's quota and block legitimate requests. Consider applying appropriate validation to GET requests as well.
Conflicts in recipeApi.ts (error messages) and test-recipe-api.ts: kept both the rate-limit/quota messages and the CONFLICT message, and both the batched insert test and the outdated-version test.
…re rate limiting - __typename now counts toward the total field and alias limits, so a fragment chain of __typename cannot expand to 2^n fields unchecked. It still does not count as a top-level field or as nesting. - A GET that carries a query needs the same X-Requested-With header as a POST. Only requests that run an operation are counted toward the request limit, so malformed or cross-site GETs cannot use up a visitor's quota.
|
Addressed the two remaining points from the second review, and merged the latest
Locally: format, lint, typecheck and 320 unit tests pass. |
Changes
Request limit
apps/api/src/apiLimits.ts. Each client (IP address, using the same key as the auth limiter, so it works behind Apache) may send 300 GraphQL requests per minute. Beyond that the API answers429withRetry-Afterand codeRATE_LIMITED.Query size (validation rule, runs before any resolver)
QUERY_TOO_COMPLEXif it has more than 10 aliases, 3 top-level fields, 300 fields after fragments are expanded, or more than 8 levels of nesting.a1: recipes(...) a2: recipes(...) …from multiplying database work in one request.__schema,__type) is not counted, so GraphiQL keeps working.Content-Length) are refused with413before parsing. A maximal recipe is far smaller.Recipe creation quota
RATE_LIMITED, withretryAfterSecondsuntil the oldest one in the window is an hour old) and 1000 in total (QUOTA_EXCEEDED).Batched inserts
INSERTper table (unnest(...) WITH ORDINALITY; positions come from the ordinality) instead of one per row. A 100-ingredient recipe now takes 3 statements instead of 200+.Other
createAppcan override. The browser-test server raises the request limit, because every scenario runs from 127.0.0.1.RATE_LIMITED(also a bare HTTP 429) andQUOTA_EXCEEDED.docs/recipe-api.md.Validation
npm run checkpasses (283 unit tests). NewapiLimits.test.ts:contracts/operations.graphqlpasses the limits, and so does GraphiQL's introspection queryrecipesquery, a 4-top-level-field query, a too-deep query and an exponential fragment chain are rejected429+Retry-Afterwhen the limit is 2, an alias bomb getsQUERY_TOO_COMPLEX, and a body over 1 MB gets413test:api(PostgreSQL 16), new cases:nullnotes and amounts such as0.1and1234.5678, plus step numbers and tagsQUOTA_EXCEEDEDtest:dband the real-database browser tests (recipe-api.spec.ts,auth-cookie.spec.ts) pass locally.Notes
AUTH_TRUST_PROXY=trueon the VM, asdocs/auth-improvements.mdalready prescribes for Apache. Without it every request arrives from 127.0.0.1, and 300/min becomes a limit for the whole site (the auth limiter has the same dependency).AI usage
Written with Claude Code (Anthropic) to address a teammate's issue. Please review the diff as you would any other contribution.
Closes #119